package xcmg.device.service.announcement;

import com.github.pagehelper.PageInfo;
import yb.ecp.fast.infra.util.PageHelperPlus;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import xcmg.device.dao.entity.DataDictionaryDO;
import xcmg.device.dao.entity.announcement.BasicAnnouncementDO;
import xcmg.device.dao.entity.announcement.BasicAttachmentDO;
import xcmg.device.dao.entity.announcement.BasicCommentDO;
import xcmg.device.dao.entity.setting.WeChatConfigDO;
import xcmg.device.dao.mapper.CompanyDealerMapper;
import xcmg.device.dao.mapper.DataDictionaryMapper;
import xcmg.device.dao.mapper.WeChatConfigMapper;
import xcmg.device.dao.mapper.announcement.BasicAnnouncementAuthMapper;
import xcmg.device.dao.mapper.announcement.BasicAnnouncementMapper;
import xcmg.device.dao.mapper.announcement.BasicAttachmentMapper;
import xcmg.device.dao.mapper.announcement.BasicCommentMapper;
import xcmg.device.infra.BeanUtil;
import xcmg.device.infra.ErrorCode;
import xcmg.device.infra.FileUtil;
import xcmg.device.service.vo.announcement.BasicAnnouncementVO;
import xcmg.device.service.vo.announcement.BasicAttachmentVO;
import xcmg.device.service.vo.announcement.BasicCommentVO;
import yb.ecp.fast.feign.FastGenClient;
import yb.ecp.fast.infra.infra.ActionResult;
import yb.ecp.fast.infra.infra.PageCommonVO;
import yb.ecp.fast.infra.infra.SearchCommonVO;
import yb.ecp.fast.infra.infra.log.LogHelper;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class BasicAnnouncementService {

    @Autowired
    private CompanyDealerMapper companyDealerMapper;

    @Autowired
    private BasicAnnouncementMapper basicAnnouncementMapper;

    @Autowired
    private BasicAttachmentMapper basicAttachmentMapper;

    @Autowired
    private BasicCommentMapper basicCommentMapper;

    @Autowired
    private BasicAttachmentService basicAttachmentService;

    @Autowired
    private FastGenClient fastGenClient;

    @Autowired
    private WeChatConfigMapper weChatConfigMapper;

    @Autowired
    private DataDictionaryMapper dataDictionaryMapper;

    @Value("${spring.file.download.path}")
    private String filePath;

    @Autowired
    private HttpServletResponse response;

    @Autowired
    private BasicAnnouncementAuthMapper basicAnnouncementAuthMapper;

    /**
     * 公告类型
     */
    private static final String PARENT_CODE_GGLX = "GGLX";

    /**
     * 通告信息查询
     *
     * @param condition
     * @return
     */
    public PageCommonVO list(SearchCommonVO<BasicAnnouncementVO> condition) {
        PageCommonVO result = new PageCommonVO();
        //按照px降序，操作时间降序
        PageHelperPlus.orderBy("px desc,create_date desc");
        PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());
        BasicAnnouncementVO announcementVO = condition.getFilters();
        List<BasicAnnouncementDO> doList = basicAnnouncementMapper.list(announcementVO);
        List<BasicAnnouncementVO> voList = new ArrayList<>();
        for (BasicAnnouncementDO entity : doList) {
            BasicAnnouncementVO model = new BasicAnnouncementVO();
            BeanUtils.copyProperties(entity, model);
            model.setTypeName(entity.getType() == null ? null : getTypeNameByCode(entity.getType()));
            if (entity.getPx() != 0) {
                model.setIsHeader(1);
            } else {
          model.setIsHeader(0);
        }
        voList.add(model);
      }
      result.setPageInfo(new PageInfo(doList));
      result.setPageInfoList(voList);
      return result;
    }


    /**
     *
     * @return
     */
    public List<BasicAnnouncementVO> listActivity() {
        WeChatConfigDO configDO = weChatConfigMapper.item();
        List<BasicAnnouncementDO> doList;
            doList = basicAnnouncementMapper.listActivity(configDO.getOrgId());
        List<BasicAnnouncementVO> voList = new ArrayList<>();
        for (BasicAnnouncementDO entity : doList) {
            BasicAnnouncementVO model = new BasicAnnouncementVO();
            BeanUtils.copyProperties(entity, model);
            model.setTypeName(entity.getType() == null ?null:getTypeNameByCode(entity.getType()));
            voList.add(model);
        }
        return voList;
    }

    private String getTypeNameByCode(String code) {
        DataDictionaryDO dataDictionaryDO = dataDictionaryMapper.itemByCode(PARENT_CODE_GGLX, code);
        if (null == dataDictionaryDO) {
            return StringUtils.EMPTY;
        }
        return dataDictionaryDO.getName();
    }


    /**
     * 代理商通告信息查询
     * @param condition
     * @return
     */
    public PageCommonVO listByDealer(SearchCommonVO<BasicAnnouncementVO> condition) {
        PageCommonVO result = new PageCommonVO();
        //按照px 排序
        PageHelperPlus.orderBy("px desc,create_date desc");
        PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());
        //根据供应商查询通告信息
        List<BasicAnnouncementDO> doList = basicAnnouncementMapper.listByDealer(condition.getFilters());
        List<BasicAnnouncementVO> voList = new ArrayList<>();
        for (BasicAnnouncementDO entity : doList) {
            BasicAnnouncementVO model = new BasicAnnouncementVO();
            BeanUtils.copyProperties(entity, model);
            if (entity.getPx() != 0) {
                model.setIsHeader(1);
            } else {
                model.setIsHeader(0);
            }
            voList.add(model);
        }
        result.setPageInfo(new PageInfo(doList));
        result.setPageInfoList(voList);
        return result;
    }

    /**
     * 新增通告信息
     * @param model
     * @return
     */
    @Transactional
    public ErrorCode add(BasicAnnouncementVO model){
        //设置默认的有效期（当前日期-9999）
        if(null == model.getValidateStart()){
            model.setValidateStart(new Date());
        }
        if(null == model.getValidateEnd()){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            try{
                model.setValidateEnd(sdf.parse("9999-12-31"));
            }catch (Exception e){
                return ErrorCode.Failure;
            }
        }
        ErrorCode errorCode = checkBasicAnnouncementVO(model);
        if (null != errorCode) {
            return errorCode;
        }
        //是否置顶
        if(model.getIsHeader()==1){
            model.setPx(basicAnnouncementMapper.countPxByOrgId(model.getOrgId()));
        }else{
            model.setPx(0);
        }
        //判断结果
        if(basicAnnouncementMapper.insert(model)==0){
            return ErrorCode.Failure;
        }
        ErrorCode er=basicAttachmentService.add(model.getBasicAttachmentList());
        if(0 != er.getCode()){
            return ErrorCode.Failure;
        }
        return ErrorCode.Success;
    }

    /**
     * 输入校验
     * @param model
     * @return
     */
    private ErrorCode checkBasicAnnouncementVO(BasicAnnouncementVO model) {
        if(StringUtils.isBlank(model.getTitle())){
            return ErrorCode.AnnouncementTitleIsEmpty;
        }
        if(!model.isActivity() && StringUtils.isBlank(model.getBody())){
            return ErrorCode.AnnouncementBodyIsEmpty;
        }
        if(StringUtils.isBlank(model.getClick())){
            return ErrorCode.AnnouncementClickIsEmpty;
        }
        return null;
    }

    /**
     * 更新通告信息
     * @param model
     * @return
     */
    @Transactional
    public ErrorCode update(BasicAnnouncementVO model){
        ErrorCode errorCode = checkBasicAnnouncementVO(model);
        if (null != errorCode) {
            return errorCode;
        }

        //是否置顶
        if(model.getIsHeader()==1){
            model.setPx(basicAnnouncementMapper.countPxByOrgId(model.getOrgId()));
        }else{
            model.setPx(0);
        }
        if(basicAnnouncementMapper.update(model)==0){
            return ErrorCode.Failure;
        }
        //根据AnnouncementId删除当下所有的附件信息
       /* BasicAttachmentVO basicAttachmentVO =new BasicAttachmentVO();
        basicAttachmentVO.setAnnouncementId(model.getId());*/
        basicAttachmentMapper.updateDelByAnnouncementId(model.getId());
        //批量添加附件信息
        ErrorCode er=basicAttachmentService.add(model.getBasicAttachmentList());
        if(0 != er.getCode()){
            return ErrorCode.Failure;
        }
        return ErrorCode.Success;
    }

    /**
     * 单条通告信息查询
     * @param id
     * @return
     */
    public BasicAnnouncementVO item(String id){
        BasicAnnouncementDO entity=basicAnnouncementMapper.selectByPrimaryKey(id);
        if(entity==null){
            return null;
        }
        BasicAnnouncementVO model=new BasicAnnouncementVO();
        BeanUtils.copyProperties(entity,model);
        model.setTypeName(entity.getType() == null ?null:getTypeNameByCode(entity.getType()));
        if(entity.getPx()!=0){
            model.setIsHeader(1);
        }else{
            model.setIsHeader(0);
        }
        model.setDealerNames(basicAnnouncementAuthMapper.listReceiverNames(id, 0));
        model.setUserNames(basicAnnouncementAuthMapper.listReceiverNames(id, 1));
        return model;
    }

    /**
     * 删除通告信息
     * 支持多个
     * @param ids
     * @return
     */
    @Transactional
    public ErrorCode remove(List<String> ids){
        if(basicAnnouncementMapper.updateDel(ids)==0){
            return ErrorCode.Failure;
        }
        for(String id : ids){
            //根据通告信息查询附件信息
            BasicAttachmentVO vo =new BasicAttachmentVO();
            vo.setAnnouncementId(id);
            List<BasicAttachmentDO> attachmentDOS = basicAttachmentMapper.list(vo);
            List<String> attachmentIds = new ArrayList<>();
            for (BasicAttachmentDO basicAttachmentDO:attachmentDOS) {
                attachmentIds.add(basicAttachmentDO.getId());
            }

            if(!(attachmentIds.isEmpty())){
                //删除对应的附件信息
                if(basicAttachmentMapper.updateDel(attachmentIds)==0){
                    return ErrorCode.Failure;
                }
            }
            //根据通告信息查询评论信息
            BasicCommentVO basicCommentVO =new BasicCommentVO();
            basicCommentVO.setAnnouncementId(id);
            List<BasicCommentDO> basicCommentDOS = basicCommentMapper.list(basicCommentVO);
            List<String> commentIds = new ArrayList<>();
            for (BasicCommentDO basicCommentDO:basicCommentDOS) {
                commentIds.add(basicCommentDO.getId());
            }
            if(!(commentIds.isEmpty())){
                //删除对应的评论信息
                if(basicCommentMapper.updateDel(commentIds)==0){
                    return ErrorCode.Failure;
                }
            }
        }
        return ErrorCode.Success;
    }

    /**
     * 单个附件信息上传
     * @param file
     * @return
     * @throws Exception
     */
    public String uploadAttach(MultipartFile file) throws Exception{
        ActionResult<String> textResult = fastGenClient.textGuid();
        String announceId = textResult.getValue();
         //定义一个空字符串
        String fileName="";
        try{
            fileName= announceId + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            FileUtil.uploadFile(file,filePath+"announcement_request_attach/", fileName);
        }catch(Exception e){
            LogHelper.fatal("BasicAnnouncementService#uploadAttach is error.", e);
            throw new Exception(e);
        }
        return fileName;
    }

    /**
     * 单个下载附件
     * @param name
     * @throws Exception
     */
    public void downloadAttach(String name,String oldName) throws Exception{
        FileUtil.downLoadFileUseOldName(response,filePath+"announcement_request_attach/",name,oldName);
    }

    /**
     * 小程序端通知资讯分页
     * @param condition
     * @return
     */
    public PageCommonVO miniPage(SearchCommonVO<BasicAnnouncementVO> condition) {
        PageCommonVO result = new PageCommonVO();
        PageHelperPlus.orderBy("create_date desc");
        PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());
        //根据供应商查询通告信息
        List<BasicAnnouncementDO> doList = basicAnnouncementMapper.miniPage(condition.getFilters());
        List<BasicAnnouncementVO> voList = new ArrayList<>();
        for (BasicAnnouncementDO entity : doList) {
            BasicAnnouncementVO model = new BasicAnnouncementVO();
            BeanUtils.copyProperties(entity, model);
            voList.add(model);
        }
        result.setPageInfo(new PageInfo(doList));
        result.setPageInfoList(voList);
        return result;
    }

    /**
     * 通知资讯详情
     * @param id
     * @return
     */
    public BasicAnnouncementVO getById(String id){
        BasicAnnouncementDO entity = basicAnnouncementMapper.selectByPrimaryKey(id);
        if(entity == null){
            return null;
        }
        BasicAnnouncementVO model = new BasicAnnouncementVO();
        BeanUtils.copyProperties(entity, model);
        model.setTypeName(entity.getType() == null ? null : getTypeNameByCode(entity.getType()));

        //查询通知资讯附件
        BasicAttachmentVO attachmentVO = new BasicAttachmentVO();
        attachmentVO.setAnnouncementId(entity.getId());
        List<BasicAttachmentDO> doList = basicAttachmentMapper.list(attachmentVO);
        List<BasicAttachmentVO> voList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(doList)){
            voList = BeanUtil.do2bo4List(doList, BasicAttachmentVO.class);
        }
        model.setBasicAttachmentList(voList);

        return model;
    }
}